/**  
* @Title: AuthController.java
* @Package cn.com.gzheroli.auth  
* @Description: TODO(用一句话描述该文件做什么)  
* @author 李长荣  
* @date 2017年6月8日  
* @version V1.0  
*/
package cn.com.gzheroli.auth;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.bfw.service.AuthService;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.tag.vo.vue.VueTreeBean;


/**  
* @ClassName:AuthController 
* @Description: TODO(这里用一句话描述这个类的作用)  
* @author 李长荣  
* @date 2017年6月8日  
*/
@Controller
@RequestMapping("/api/authController")
public class AuthController {
	private static final Logger logger = Logger.getLogger(AuthController.class);
	@Autowired
	private AuthService authService;
	@Resource
	private CommonService commonService;
	@Resource
	private SystemService systemService;
	@Autowired
    private SpringRedisCache cache;
	@RequestMapping(value = "getAuthMenu")
	@ResponseBody
	public AjaxJson getAuthMenu(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		//String roleId = request.getParameter("roleid");
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		
		TSUser user=client.getUser();
		String deptId=user.getDepartId();
		if(user.getDepartId()!=null&&!user.getDepartId().trim().equals("")){
			TSDepart depart=commonService.get(TSDepart.class, user.getDepartId());
			if(depart.getLevelNo()!=null&&!depart.getLevelNo().trim().equals("")){
				String levelNo=depart.getLevelNo();
				levelNo=levelNo.substring(0, 3);
				List<TSDepart> depts=commonService.findByProperty(TSDepart.class, "levelNo", levelNo);
				if(depts!=null&&!depts.isEmpty()){
					TSDepart pdepart=depts.get(0);
					deptId=pdepart.getId();
				}
			}
		}
		
		String parentId=request.getParameter("parentId");
		List<Map<String,Object>> authMenu=authService.getAuthMenu(user,parentId);
		Map retMap=new HashMap();
		retMap.put("deptId", deptId);
		retMap.put("user", user);
		retMap.put("authMenu", authMenu);
		j.setObj(retMap);
		j.setMsg("获取权限菜单成功");
		return j;
	}
	@RequestMapping(value = "getAuthMenuOperation")
	@ResponseBody
	public AjaxJson getAuthMenuOperation(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		String menuId= request.getParameter("menuId");
		String path= request.getParameter("path");
		List<Map<String,Object>> opList=authService.getAuthMenuOperation(client.getUser(),menuId,path);
		j.setObj(opList);
		j.setMsg("获取菜单操作代码成功");
		return j;
	}
	/**
	 * 
	* @Title: refreshTable  
	* @Description:更新数据库表及字段信息到缓存里面
	* @param @param request
	* @param @return    参数  
	* @return AjaxJson    返回类型  
	* @throws
	 */
	@RequestMapping(value = "refreshTable")
	@ResponseBody
	public AjaxJson refreshTable(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		systemService.getInitAllTables("");
		j.setMsg("获取菜单操作代码成功");
		return j;
	}
	 @RequestMapping(value="getDepartTree")
		@ResponseBody
		public AjaxJson getDepartTree(HttpServletRequest request) throws Exception{
	        String data=null;
	        AjaxJson j=new AjaxJson();
	        String parentid=request.getParameter("parentid")==null?"":request.getParameter("parentid");
	        //JSONArray jsons =builderComboTree(parentid);
	        //data=jsons.toString();    
	        //List<Map<String,Object>> deptTree=builderComboTree(parentid);
	        String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
			Client client=cache.getCache(token, Client.class);
			if(client==null||client.getUser()==null){
				j.setSuccess(false);
				j.setMsg("尚未登录,请登录!");
				return j;
			}
			TSUser tuser=client.getUser();
	        Map para=new HashMap();
			if(parentid==null||parentid.equals(""))
				para.put("pid",null);
			else {
				para.put("pid", parentid);
			}
			para.put("status", "1");
			List<Map<String,Object>> deptTree=authService.getDepartList(para,tuser);
	        j.setObj(deptTree);
	        j.setSuccess(true);
	        return j;
		}
	 /**
		 * 
		* @Title: getDepartZtree  
		* @Description: 根据权限返回ztree部门结构  
		* @param @param request
		* @param @param comboTree
		* @param @return    参数  
		* @return List<Map>    返回类型  
		* @throws
		 */
		@RequestMapping(value = "getDepartZtree")
		@ResponseBody
		public AjaxJson getDepartZtree(HttpServletRequest request, ComboTree comboTree) {
			AjaxJson j = new AjaxJson();
			String msg = "获取成功";
			boolean success = true;
			//String parentid=request.getParameter("parentid")==null?"":request.getParameter("parentid");
			//Client client=cache.getCache(request.getSession().getId(), Client.class);
			String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
			Client client=cache.getCache(token, Client.class);
			if(client==null||client.getUser()==null){
				j.setSuccess(false);
				j.setMsg("尚未登录,请登录!");
				return j;
			}
			TSUser tuser=client.getUser();
			String departId=tuser==null||tuser.getDepartId()==null?"":tuser.getDepartId();
			TSDepart dept=commonService.get(TSDepart.class, departId);
			//String isNeedCheck=dept==null||dept.getIsNeedCheck()==null?"":dept.getIsNeedCheck();
			//String parentDepartId=dept.getParentId();
			String parentid=comboTree.getId()==null?"":comboTree.getId();
			
			List<Map<String, Object>> deptList=authService.getDepartZtree(tuser,parentid);
			List<Map> comboTrees = new ArrayList<Map>();
			if(null!=deptList&&!deptList.isEmpty()){
				/*if(dept.getIsNeedCheck()!=null&&dept.getIsNeedCheck().trim().equals("1")){
					Map ptreeMap = new HashMap();
					ptreeMap.put("name", dept.getDepartName());
					ptreeMap.put("id", dept.getId());
					ptreeMap.put("pId", dept.getParentId());
					ptreeMap.put("isParent", true);
					comboTrees.add(ptreeMap);
				}*/
				
				for(Map dep:deptList){
					Map treeMap = new HashMap();
					treeMap.put("name", dep.get("departName")==null?"":dep.get("departName").toString());
					treeMap.put("id", dep.get("id")==null?"":dep.get("id").toString());
					treeMap.put("pId", dep.get("parentId")==null?"":dep.get("parentId").toString());
					treeMap.put("isParent", dep.get("parentId")==null?"":dep.get("parentId").toString());
					Long subDeptCount=Long.parseLong(dep.get("subCount")==null?"0":dep.get("subCount").toString());
					
					if(subDeptCount>0)
						treeMap.put("isParent", true);
					else
						treeMap.put("isParent", false);
					comboTrees.add(treeMap);
		        }
			}else{
				Map treeMap = new HashMap();
				treeMap.put("name", dept.getDepartName());
				treeMap.put("id", dept.getId());
				treeMap.put("isParent", false);
				comboTrees.add(treeMap);
			}
			j.setObj(comboTrees);
			j.setMsg(msg);
			j.setSuccess(success);
			return j;
		}
		/**
		 * 
		* @Title: getAllDepartZtree  
		* @Description: 返回所有ztree部门结构  
		* @param @param request
		* @param @param comboTree
		* @param @return    参数  
		* @return List<Map>    返回类型  
		* @throws
		 */
		@RequestMapping(value = "getAllDepartZtree")
		@ResponseBody
		public AjaxJson getAllDepartZtree(HttpServletRequest request, ComboTree comboTree) {
			AjaxJson j=new AjaxJson();
			boolean success=true;
			String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
			Client client=cache.getCache(token, Client.class);
			if(client==null||client.getUser()==null){
				j.setSuccess(false);
				j.setMsg("尚未登录,请登录!");
				return j;
			}
			TSUser tuser=client.getUser();
			String msg="获取成功";
			String parentid=comboTree.getId()==null?"":comboTree.getId();
			TSDepart parentDepart = null;
			if(parentDepart!=null)
				parentDepart = commonService.get(TSDepart.class, parentid);
			String selfId=request.getParameter("selfId");
			List<Map<String, Object>> deptList=authService.getAllDepartZtree(tuser,parentid);
			List<Map> comboTrees = new ArrayList<Map>();
			if(null!=deptList&&!deptList.isEmpty()){
				/*Map ptreeMap = new HashMap();
				ptreeMap.put("name", dept.getDepartName());
				ptreeMap.put("id", dept.getId());
				ptreeMap.put("pId", dept.getParentId());
				ptreeMap.put("isParent", true);
				comboTrees.add(ptreeMap);*/
				for(Map dep:deptList){
					Map treeMap = new HashMap();
					treeMap.put("name", dep.get("departName")==null?"":dep.get("departName").toString());
					treeMap.put("id", dep.get("id")==null?"":dep.get("id").toString());
					treeMap.put("pId", dep.get("parentId")==null?"":dep.get("parentId").toString());
					treeMap.put("isParent", dep.get("parentId")==null?"":dep.get("parentId").toString());
					Long subDeptCount=commonService.getCountForJdbc("select count(*) from T_S_DEPART t where t.PARENT_ID='"+dep.get("id").toString()+"' and t.STATUS='1' and t.IS_NEED_CHECK='1'");
					if(subDeptCount>0)
						treeMap.put("isParent", true);
					else
						treeMap.put("isParent", false);
					comboTrees.add(treeMap);
		        }
			}else{
				Map treeMap = new HashMap();
				treeMap.put("name", parentDepart.getDepartName());
				treeMap.put("id", parentDepart.getId());
				treeMap.put("isParent", false);
				comboTrees.add(treeMap);
			}
			j.setObj(comboTrees);
			j.setMsg(msg);
			j.setSuccess(success);
			return j;
		}
		@RequestMapping(value = "getDepart")
		@ResponseBody
		public List<VueTreeBean> getDepart(HttpServletRequest request, VueTreeBean comboTree) {
			//String parentid=request.getParameter("parentid")==null?"":request.getParameter("parentid");
			//Client client=cache.getCache(request.getSession().getId(), Client.class);
			String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
			Client client=cache.getCache(token, Client.class);
			TSUser tuser =client==null?null:client.getUser();
			String departId=tuser==null||tuser.getDepartId()==null?"":tuser.getDepartId();
			String selfId=request.getParameter("selfId");
			return authService.getDepart(comboTree, departId, tuser);
		}
}
